/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-26 18:32:44
 * @Description  : 章节接口验证中间件
 */

const Joi = require('joi')
const { Op } = require('sequelize')
const R = require('@/models/Response')
const { Chapter } = require('@/models/model')
const { ERROR_SYSTEM_CODE, ERROR_USER_CODE } = require('@/constants/errorCode')
const { IS_INTEGER, IS_UNSAFE_INTEGER } = require('@/constants/joiSchema')
const { dumpCheck: globalDumpCheck } = require('@/utils/dumpCheck')

const chapterSchema = {
  chapterIds: Joi.array().items(IS_UNSAFE_INTEGER),
  chapterId: IS_UNSAFE_INTEGER,
  page: IS_INTEGER.min(1).default(1),
  pageSize: IS_INTEGER.min(1).default(999),
  name: Joi.string().min(1).max(255),
  examId: IS_UNSAFE_INTEGER,
  pid: IS_UNSAFE_INTEGER
}

const dumpCheck = {
  /**
   * @author: Hejh(3010733382@qq.com)
   * @description: 验证章节ID的合法性
   * @param {array<string>} chapterIds 章节ID数组
   * @param {boolean} isLink 需要为外链
   * @param {boolean} isChapterTo 需要为内部章节
   */
  checkChapterIds: async (chapterIds) => {
    let newchapterIds = [...new Set(chapterIds)]
    // 不能出现重复的
    if (newchapterIds.length !== chapterIds.length) {
      return false
    }

    newchapterIds = newchapterIds.map((item) => BigInt(item))

    if (newchapterIds.length === 0) {
      return true
    }

    // 查看不重复的和数据库的是否对的上
    const myWhere = {
      id: {
        [Op.in]: newchapterIds
      }
    }
    const chapters = await Chapter.findAll({
      where: myWhere
    })
    if (chapters.length !== newchapterIds.length) {
      return false
    }
    return true
  }
}

/**
 * @description 章节列表查询的参数验证
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
module.exports.listChapterValidate = async (ctx, next) => {
  const schema = Joi.object({
    page: chapterSchema.page,
    pageSize: chapterSchema.pageSize,
    pid: chapterSchema.pid,
    examId: chapterSchema.examId
  }).validate(ctx.query)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  ctx.newQuery = schema.value
  await next()
}

/**
 * @description 创建章节时的参数验证
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
module.exports.createChapterValidate = async (ctx, next) => {
  const schema = Joi.object({
    name: chapterSchema.name.required(),
    pid: chapterSchema.pid.required(),
    examId: chapterSchema.examId.required()
  }).validate(ctx.request.body)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }
  const { pid, examId } = ctx.request.body

  // TODO 验证pid的合法性
  const b4 = await globalDumpCheck.checkChapterIds([pid], true)
  if (!b4) {
    ctx.body = R.error(ERROR_USER_CODE.CHAPTER_ID_ERROR)
    return
  }
  const b5 = await globalDumpCheck.checkExamIds([examId])
  if (!b5) {
    ctx.body = R.error(ERROR_USER_CODE.EXAM_ID_ERROR)
    return
  }
  await next()
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 更新章节时的参数验证
 * @param {*} ctx
 * @param {*} next
 */
module.exports.updateChapterValidate = async (ctx, next) => {
  const schema = Joi.object({
    chapterId: chapterSchema.chapterId.required(),
    name: chapterSchema.name.required(),
    pid: chapterSchema.pid.required(),
    examId:chapterSchema.examId
  }).validate(ctx.request.body)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }

  const { chapterId, pid } = ctx.request.body

  //TODO 验证 pid 和 chapterId的合法性
  const b1 = globalDumpCheck.checkChapterIds([chapterId])
  if (!b1) {
    ctx.body = R.error(ERROR_USER_CODE.CHAPTER_ID_ERROR)
    return
  }

  const b2 = await globalDumpCheck.checkChapterIds([pid], true)
  if (!b2) {
    ctx.body = R.error(ERROR_USER_CODE.CHAPTER_ID_ERROR)
    return
  }

  await next()
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除章节接口的参数验证
 * @param {*} ctx
 * @param {*} next
 */
module.exports.delChaptersValidate = async (ctx, next) => {
  const schema = Joi.object({
    chapterIds: chapterSchema.chapterIds.required()
  }).validate(ctx.request.body)

  if (schema.error) {
    ctx.body = R.error(ERROR_SYSTEM_CODE.PARAMS_SCHEMA_ERROR)
    return
  }

  const { chapterIds } = ctx.request.body

  // 验证章节ID数组的合法性
  const b4 = await dumpCheck.checkChapterIds(chapterIds)
  if (!b4) {
    ctx.body = R.error(ERROR_USER_CODE.CHAPTER_DEL_ERROR)
    return
  }
  await next()
}
